#include "PrecompiledHeaders.h"
#include "LevelLocks.h"
#include "Constants.h"
#include "Utilities.h"
#include "Level.h"
 
#include <string>
 
std::string LevelLocks::filename = "";

void LevelLocks::unlockAll(LevelVector *levels)
{
    // set all levels (except) first unlocked
    LevelVector::iterator i;
    for(i = levels->begin(); i != levels->end(); i++) {
        i->setUnlocked();
    }
}

/*
 * Lock/Unlock levels from file or from default
 */
void LevelLocks::setLevelLocks(LevelVector *levels)
{
    filename = Constants::RESOURCES_FOLDER + "levels/levels.locks";
    if(fileExists(filename))
    {
        int stringLen;
        char levelName[100];
        std::fstream file;
        file.open(filename.c_str(), std::ios::in | std::ios::binary);
        
        // Test if the file is empty
        file.seekg(0, std::ios_base::end);
        if ((int)file.tellg() == 0) {
             printf("Empty lock file\n");
             file.close();
             return;
        }
        file.seekg(0, std::ios_base::beg);
        
        while(!file.eof()) {
            // read string length
            file.read((char *)&stringLen, sizeof(int));
            // read string
            file.read((char *)&levelName, stringLen);
            levelName[stringLen] = '\0';
            setLevelLock(levels, levelName);
        }
        file.close();
    }
    else
    {
        levels->begin()->setUnlocked();
    }
}

/*
 * Lock a level by name
 */
void LevelLocks::setLevelLock(LevelVector *levels, std::string levelName)
{
    LevelVector::iterator i;
    for(i = levels->begin(); i != levels->end(); i++) {    
        if(i->name == levelName) {
            i->setUnlocked();
            printf("UNLOCKED %s\n", levelName.c_str());
            return;
        }
    }
}

/*
 * Save the unlocked levels
 */
void LevelLocks::saveLevelLocks(LevelVector *levels)
{
    int stringLen;
    LevelVector::iterator i;
    std::fstream file;
    file.open(filename.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
    for(i = levels->begin(); i != levels->end(); i++) {
        if(!i->isLocked()) {
            // write string length
            stringLen = (int)i->name.size();
            file.write((char *)&stringLen, sizeof(int));
            // write string
            file.write(i->name.c_str(), stringLen);
            printf("WROTE %s\n", i->name.c_str());
        }
    }
    file.flush();
    file.close();
}

